# -*- coding:utf-8 -*-

import os, sys, time

import tornado.web
import tornado.httpserver
import tornado.ioloop

from tornado.options     import define, options
from utils.routes        import route
from utils               import mongo
from configure           import config
from utils.fastdfs_utils import DfsUtils
from mq.amqp             import Rabbitmq
from service             import sn_id

from loog.mylog           import flogger as logger


class Application(tornado.web.Application):

    def __init__(self):

        # TODO 各项初始化操作未成功的处理

        mongo.initMongoDb(host=config.MONGODB_HOST,
                          port=config.MONGODB_PORT,
                          dbuser=config.MONGODB_USERNAME,
                          dbpass=config.MONGODB_PASSWORD)

        print 'Inited MongoDB'
        logger.info('Inited MongoDB')

        Rabbitmq()
        print 'Inited RabbitMQ'
        logger.info('Inited RabbitMQ')

        options["fastdfs_client"] = DfsUtils()
        logger.info('Inited FastDFS')
        print 'Inited FastDFS'

        io_loop = tornado.ioloop.IOLoop.instance()
        io_loop.add_timeout(time.time() + 20, sn_id.loadSnIds)    # 20秒后加载

        handlers = route.get_routes()
        settings = {
            'debug'         : True,
            'template_path' : os.path.join(options.root_dir, 'template'),
            'static_path'   : os.path.join(options.root_dir, 'static'),
            'cookie_secret' : 'NyM8vWu0Slec0GLonsdI3ebBX0VEqU3Vm8MsHiN5rrc=',
        }
        tornado.web.Application.__init__(self, handlers, **settings)


def main():

    src_dir  = os.path.dirname(__file__)
    src_dir  = os.path.abspath(src_dir)
    root_dir = os.path.dirname(src_dir)

    sys.path.insert(0, src_dir)
    define('src_dir', src_dir)
    define('root_dir', root_dir)
    define('port', default=config.SERVER_PORT, help='', type=int)
    options.parse_command_line()

    http_server = tornado.httpserver.HTTPServer(Application())
    http_server.listen(options.port)

    logger.info('Server Started...')
    print 'Server Started...'

    tornado.ioloop.IOLoop.instance().start()


if __name__ == "__main__":
    main()

